<script setup>
import {onBeforeRouteUpdate} from 'vue-router'
import {ArrowLeftBold, CircleClose, Edit, Location, Message, Plus, Refresh} from "@element-plus/icons-vue";
import router from "@/router";
import {nextTick, reactive, ref, toRef, watch, onMounted} from "vue";
import {getCurMerchant} from "@/api/merchant";
import {ElMessage, ElMessageBox} from "element-plus";
import {
  closeStoreById,
  deleteStoreById,
  getStoreById,
  getStoreListByMerchantId,
  insertANewStore,
  updateStoreById
} from "@/api/store";
import {useRoute} from "vue-router";
// 在setup中添加路由守卫
onBeforeRouteUpdate((to, from) => {
  // 切换店铺时关闭编辑抽屉
  drawerVisible.value = false
})


//----------变量------------------------------------------------------------
// 用route接收传来的参数
const route = useRoute();
const storeId = ref(parseInt(route.params.id))
console.log("当前storeId:", storeId.value)
// 当前店铺
const curStore = ref({});
const curStoreInfo = ref({});
// 编辑店铺信息窗口
const drawerVisible = ref(false)
const direction = ref('rtl')
// *****编辑信息相关变量*****
// 类别
const categoriesOptions = [
  {
    value: '美食', label: '美食',
    children: [
      {value: '川菜', label: '川菜'},
      {value: '粤菜', label: '粤菜'},
      {value: '湘菜', label: '湘菜'},
      {value: '火锅', label: '火锅'},
      {value: '烧烤', label: '烧烤'},
      {value: '日料', label: '日料'},
      {value: '韩餐', label: '韩餐'},
      {value: '小吃快餐', label: '小吃快餐'},
      {value: '西餐', label: '西餐'},
      {value: '甜品', label: '甜品'},
    ],
  },
  {
    value: '饮品', label: '饮品',
    children: [
      {value: '咖啡', label: '咖啡'},
      {value: '奶茶', label: '奶茶'},
      {value: '果汁', label: '果汁'},
      {value: '冰淇淋', label: '冰淇淋'},
    ],
  },
  {
    value: '购物', label: '购物',
    children: [
      {value: '百货商场', label: '百货商场'},
      {value: '超市便利', label: '超市便利'},
      {value: '服装鞋包', label: '服装鞋包'},
      {value: '化妆品', label: '化妆品'},
      {value: '数码家电', label: '数码家电'},
      {value: '母婴用品', label: '母婴用品'},
      {value: '家具家居', label: '家具家居'},
    ],
  },
  {
    value: '娱乐', label: '娱乐',
    children: [
      {value: '电影院', label: '电影院'},
      {value: 'KTV', label: 'KTV'},
      {value: '密室逃脱', label: '密室逃脱'},
      {value: '桌游', label: '桌游'},
      {value: '电玩城', label: '电玩城'},
      {value: '剧本杀', label: '剧本杀'},
    ],
  },
  {
    value: '酒店', label: '酒店',
    children: [
      {value: '经济型', label: '经济型'},
      {value: '商务型', label: '商务型'},
      {value: '豪华型', label: '豪华型'},
      {value: '民宿客栈', label: '民宿客栈'},
      {value: '青年旅舍', label: '青年旅舍'},
      {value: '度假村', label: '度假村'},
    ],
  },
  {
    value: '景点', label: '景点',
    children: [
      {value: '公园', label: '公园'},
      {value: '博物馆', label: '博物馆'},
      {value: '古镇古村', label: '古镇古村'},
      {value: '游乐园', label: '游乐园'},
      {value: '海滩', label: '海滩'},
      {value: '山地景区', label: '山地景区'},
      {value: '动物园', label: '动物园'},
    ],
  },
  {
    value: '运动', label: '运动',
    children: [
      {value: '健身房', label: '健身房'},
      {value: '游泳馆', label: '游泳馆'},
      {value: '篮球馆', label: '篮球馆'},
      {value: '羽毛球馆', label: '羽毛球馆'},
      {value: '网球馆', label: '网球馆'},
      {value: '瑜伽', label: '瑜伽'},
      {value: '攀岩', label: '攀岩'},
      {value: '滑冰滑雪', label: '滑冰滑雪'},
    ],
  },
  {
    value: '其他', label: '其他',
    children: [
      {value: '宠物', label: '宠物'},
      {value: '医疗健康', label: '医疗健康'},
      {value: '教育培训', label: '教育培训'},
      {value: '生活服务', label: '生活服务'},
    ],
  },
];
// 标签
const dynamicTags = ref([])
const inputVisible = ref(false)
const inputValue = ref('')
const InputRef = ref()
// 规则
const ruleFormRef = ref()
const ruleForm = ref({
  name: '', // 乐玩电玩城
  categories: [], // ['娱乐', '电玩城']
  openingHours: [],
  coverImage: '',
  contactInfo: '', // 18888888888
  address: '', // 西安市碑林区aa路bb号
  license: '',
  photos: '',
  priceMin: '', // 50
  priceMax: '', // 500
  description: '',
})
// 规则
const rules = reactive({
  name: [
    {required: true, message: '店名不能为空', trigger: 'blur'},
    {min: 2, max: 20, message: '店名长度要在2~20个字之间', trigger: 'blur'},
  ],
  categories: [
    {
      required: true,
      message: '请选择店铺类别',
      trigger: 'blur',
    }
  ],
  coverImage: [
    {
      required: true,
      message: '请上传店铺封面',
      trigger: 'change',
    }
  ],
  openingHours: [
    {
      required: true,
      message: '请选择营业时间',
      trigger: 'change',
    }
  ],
  contactInfo: [
    {
      required: true,
      message: '请输入联系方式',
      trigger: 'blur',
    },
  ],
  address: [
    {
      required: true,
      message: '请输入详细地址',
      trigger: 'blur',
    }
  ],
  license: [
    {
      required: true,
      message: '请上传营业执照',
      trigger: 'change',
    }
  ],
  photos: [
    {
      required: true,
      message: '请上传店铺照片',
      trigger: 'change',
    }
  ],
  priceMin: [
    {
      required: true,
      message: '请输入最低价',
      trigger: 'blur',
    },
  ],
  priceMax: [
    {
      required: true,
      message: '请输入最高价',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value <= ruleForm.value.priceMin) {
          callback(new Error('最高价必须大于最低价'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    }
  ],
  description: [
    {
      required: true,
      message: '请输入店铺描述',
      trigger: 'blur',
    }
  ],
})

//----------函数------------------------------------------------------------
// 监听路由，接收传来的参数
watch(() => route.params.id, (newId) => {
  storeId.value = parseInt(newId)
  // 重置关键状态
  drawerVisible.value = false
  inputVisible.value = false
  inputValue.value = ''
  getStoreDetails()
})
// 获取当前店铺的详细信息
const getStoreDetails = () => {
  // 先重置表单状态
  ruleForm.value = {
    name: '',
    categories: [],
    openingHours: [],
    coverImage: '',
    contactInfo: '',
    address: '',
    license: '',
    photos: [],
    priceMin: '',
    priceMax: '',
    description: '',
  }
  dynamicTags.value = []
  getStoreById(storeId.value).then(res => {
    curStore.value = res.data;

    // 确保JSON字段正确解析
    if (typeof curStore.value.tags === 'string') {
      curStore.value.tags = JSON.parse(curStore.value.tags);
    }
    if (typeof curStore.value.photos === 'string') {
      curStore.value.photos = JSON.parse(curStore.value.photos);
    }

    curStoreInfo.value = JSON.parse(JSON.stringify(curStore.value)) // 深拷贝当前店铺信息
    ruleForm.value = {
      name: curStore.value.name, // 乐玩电玩城
      // el-cascader 的 v-model 需要的是一个普通数组，而不是 Ref 对象。
      categories: [curStore.value.category, curStore.value.subCategory], // ['娱乐', '电玩城']
      openingHours: parseOpeningHours(curStore.value.openingHours),
      coverImage: curStore.value.coverImage,
      contactInfo: curStore.value.contactInfo, // 18888888888
      address: curStore.value.address, // 西安市碑林区aa路bb号
      license: curStore.value.license,
      photos: Array.isArray(curStore.value.photos) ? [...curStore.value.photos] : [],
      priceMin: curStore.value.priceMin, // 50
      priceMax: curStore.value.priceMax, // 500
      description: curStore.value.description,
    }
    // 确保标签是数组
    dynamicTags.value = Array.isArray(curStore.value.tags) ?
        [...curStore.value.tags] :
        [];
  })
}
getStoreDetails()
// *****店铺信息编辑相关方法*****
const openEditDrawer = async () => {
  await getStoreDetails(); // 确保数据最新
  drawerVisible.value = true;
}
// 上传店铺封面
const handleCoverSuccess = (res, file) => {
  ruleForm.value.coverImage = res.data.url // 直接更新表单数据
}
// 上传营业执照
const handleLicenseSuccess = (res, file) => {
  ruleForm.value.license = res.data.url // 直接更新表单数据
}
// 上传店铺照片
const handlePhotoSuccess = (res, file) => {
  ruleForm.value.photos.push(res.data.url) // 直接更新表单数组
}
// 删除一个标签
const handleClose = (tag) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}
// 添加新标签时显示输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value?.input?.focus()
  })
}
// 添加标签
const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}

// 提取时间部分并格式化
function formatTime(timeStr) {
  const date = new Date(timeStr);
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
}

// 工具函数：字符串转时间范围数组
const parseOpeningHours = (str) => {
  if (!str) return [new Date(), new Date()];

  try {
    const [start, end] = str.split('-');
    const now = new Date();

    const startParts = start.split(':').map(Number);
    const endParts = end.split(':').map(Number);

    const startDate = new Date(now);
    startDate.setHours(startParts[0], startParts[1] || 0, 0, 0);

    const endDate = new Date(now);
    endDate.setHours(endParts[0], endParts[1] || 0, 0, 0);

    return [startDate, endDate];
  } catch (e) {
    console.error('解析营业时间失败:', e);
    return [new Date(), new Date()];
  }
};
// 提取时间部分并格式化
const formatOpeningHours = (dates) => {
  if (!dates || dates.length !== 2) return '';
  const format = (date) => date.toTimeString().slice(0, 5); // 输出 "HH:mm"
  return `${format(dates[0])}-${format(dates[1])}`;
};
// 确认并提交编辑
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
          '你确认提交编辑吗？',
          '温馨提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        console.log('submit!')
        const payload = {
          id: storeId.value,
          name: ruleForm.value.name,
          category: ruleForm.value.categories[0],
          subCategory: ruleForm.value.categories[1],
          tags: dynamicTags.value,
          description: ruleForm.value.description,
          openingHours: formatOpeningHours(ruleForm.value.openingHours),
          contactInfo: ruleForm.value.contactInfo,
          address: ruleForm.value.address,
          coverImage: ruleForm.value.coverImage,
          license: ruleForm.value.license,
          photos: ruleForm.value.photos,
          priceMin: ruleForm.value.priceMin,
          priceMax: ruleForm.value.priceMax,
          status: 0,
        }
        updateStoreById(payload).then(res => {
          if (res.data) {
            ElMessageBox.alert('店铺信息修改成功，请耐心等待审核', '提示', {
              confirmButtonText: '确定',
              type: 'success'
            }).then(() => {
              router.push({path: '/merchant/storeManageList/' + curStore.value.id})
              getStoreDetails()
              drawerVisible.value = false
            })
          } else {
            ElMessageBox.alert('店铺信息修改失败，请稍后再试', '提示', {
              confirmButtonText: '确定',
              type: 'error'
            }).then(() => {
              drawerVisible.value = false
            })
          }
        })
      })
    } else {
      console.log('error submit!', fields)
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}
// 取消编辑
const cancelClick = () => {
  drawerVisible.value = false
  getStoreDetails()
}
// 关停店铺
const closeStore = () => {
  ElMessageBox.confirm(
      '确定要关停店铺吗？关停后顾客将无法看到您的店铺。',
      '警告',
      {
        confirmButtonText: '确定关停',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    closeStoreById(curStore.value.id).then(res => {
      ElMessage.success("店铺已关停");
      getStoreDetails(); // 重新获取店铺信息
      window.location.reload(true);
    })
  }).catch(() => {
  });
};
// 撤回店铺申请
const withdrawApplication = () => {
  ElMessageBox.confirm(
      '确定要撤回店铺申请吗？撤回后需重新提交审核。',
      '提示',
      {
        confirmButtonText: '确定撤回',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    const updateStoreStatus = {
      id: curStore.value.id,
      status: 4 // 设置状态为已撤回
    }
    updateStoreById(updateStoreStatus).then(res => {
      if (res.data) {
        ElMessage.success("已撤回申请");
        getStoreDetails();
      } else {
        ElMessage.error("撤回申请失败，请稍后再试");
      }
    })
  }).catch(() => {
  });
};
// 重新申请
const reapplyStore = () => {
  ElMessageBox.confirm(
      '确定要重新提交店铺申请吗？',
      '提示',
      {
        confirmButtonText: '确定提交',
        cancelButtonText: '取消',
        type: 'info'
      }
  ).then(async () => {
    // 调用重新申请API（需自行实现）
    // await reapplyStoreApi(storeId.value);
    ElMessage.success("已重新提交申请");
    await getStoreDetails(); // 重新获取店铺信息
  }).catch(() => {
  });
};

</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>店铺管理详情</span>
      </div>
    </template>
    <template #default>
      <div class="default">
        <el-descriptions
            direction="vertical"
            :column="6"
            size="large"
            border
        >
          <el-descriptions-item
              label="封面"
              :rowspan="2"
              :width="140"
              align="center"
          >
            <el-image
                style="width: 150px; height: 100px"
                :src="curStoreInfo.coverImage"
            />
          </el-descriptions-item>
          <el-descriptions-item label="店名">
            {{ curStoreInfo.name }}
          </el-descriptions-item>
          <el-descriptions-item label="类别">
            {{ curStoreInfo.category }} | {{ curStoreInfo.subCategory }}
          </el-descriptions-item>
          <el-descriptions-item label="标签" :span="2">
            <el-tag
                v-for="item in curStoreInfo.tags"
                size="small"
            >
              {{ item }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="营业时间">
            {{ curStoreInfo.openingHours }}
          </el-descriptions-item>
          <el-descriptions-item label="入驻时间">
            {{ curStoreInfo.joinedAt }}
          </el-descriptions-item>
          <el-descriptions-item label="联系方式">
            {{ curStoreInfo.contactInfo }}
          </el-descriptions-item>
          <el-descriptions-item label="店铺地址">
            {{ curStoreInfo.address }}
          </el-descriptions-item>
          <el-descriptions-item label="价格区间">
            {{ curStoreInfo.priceMin }} - {{ curStoreInfo.priceMax }} 元
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="['warning','success','danger','info', 'info'][curStoreInfo.status]">
              {{ ['待审核', '已通过', '未通过', '已关停', '已撤回申请'][curStoreInfo.status] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="店铺描述">
            {{ curStoreInfo.description }}
          </el-descriptions-item>
        </el-descriptions>
        <el-divider>
          <el-icon>
            <Message/>
          </el-icon>
        </el-divider>
        <div class="edit-store-info-btn-div">
          <el-button
              v-if="curStore.status === 1"
              class="edit-store-info-btn"
              type="primary"
              @click="openEditDrawer"
          >
            <span>
              <el-icon><Edit/></el-icon>
              编辑店铺信息
            </span>
          </el-button>
          <el-button
              v-if="curStore.status === 3"
              class="edit-store-info-btn"
              type="primary"
              @click="openEditDrawer"
          >
            <span>
              <el-icon><Edit/></el-icon>
              编辑信息后重新开业
            </span>
          </el-button>
          <el-button
              v-if="curStore.status === 4"
              class="edit-store-info-btn"
              type="primary"
              @click="openEditDrawer"
          >
            <span>
              <el-icon><Edit/></el-icon>
              编辑信息后重新申请
            </span>
          </el-button>
          <!-- 待审核（status=0）：撤回申请 -->
          <el-button
              v-if="curStore.status === 0"
              class="edit-store-info-btn"
              type="warning"
              @click="withdrawApplication"
          >
            <el-icon>
              <ArrowLeftBold/>
            </el-icon>
            撤回申请
          </el-button>
          <!-- 已通过（status=1）：关停店铺 -->
          <el-button
              v-else-if="curStore.status === 1"
              class="edit-store-info-btn"
              type="danger"
              @click="closeStore"
          >
            <el-icon>
              <CircleClose/>
            </el-icon>
            关停店铺
          </el-button>
          <!-- 未通过（status=2）：重新申请 -->
          <el-button
              v-else-if="curStore.status === 2"
              class="edit-store-info-btn"
              type="info"
              @click="drawerVisible = true"
          >
            <el-icon>
              <Refresh/>
            </el-icon>
            编辑后重新申请
          </el-button>
        </div>


        <!--   编辑信息抽屉   -->
        <el-drawer
            v-model="drawerVisible"
            :direction="direction"
            :size="'50%'"
        >
          <template #header>
            <h4>编辑店铺信息</h4>
          </template>
          <template #default>
            <span>
              <el-form
                  label-width="auto"
                  ref="ruleFormRef"
                  :rules="rules"
                  :model="ruleForm"
              >
                <el-form-item label="封面"  prop="coverImage">
                  <el-upload
                      class="avatar-uploader"
                      action="/api/file/upload"
                      :show-file-list="false"
                      :on-success="handleCoverSuccess"
                  >
                    <img
                        v-if="ruleForm.coverImage"
                        :src="ruleForm.coverImage"
                        class="avatar"
                        style="height: 100px"
                        alt=""
                    />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus/>
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="店名" prop="name">
                  <el-input v-model="ruleForm.name"/>
                </el-form-item>
                <el-form-item label="类别" prop="categories">
                  <el-cascader v-model="ruleForm.categories" :options="categoriesOptions" clearable/>
                </el-form-item>
                <el-form-item label="标签">
                  <el-tag
                      v-for="tag in dynamicTags"
                      :key="tag"
                      closable
                      :disable-transitions="false"
                      @close="handleClose(tag)"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-input
                      v-if="inputVisible"
                      ref="InputRef"
                      v-model="inputValue"
                      class="w-20"
                      size="small"
                      @keyup.enter="handleInputConfirm"
                      @blur="handleInputConfirm"
                      style="max-width: 100px"
                  />
                  <el-button v-else class="button-new-tag" size="small" @click="showInput">
                    + 新标签
                  </el-button>
                </el-form-item>
                <el-form-item label="营业时间" prop="openingHours">
                  <div class="demo-range">
                    <el-time-picker
                        v-model="ruleForm.openingHours"
                        is-range
                        range-separator="至"
                        start-placeholder="开门时间"
                        end-placeholder="关门时间"
                        style="width: 250px"
                    />
                  </div>
                </el-form-item>
                <el-form-item label="联系方式" prop="contactInfo">
                  <el-input v-model="ruleForm.contactInfo"/>
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                  <el-input v-model="ruleForm.address"/>
                </el-form-item>
                <el-form-item label="营业执照" prop="license">
                  <el-upload
                      class="avatar-uploader"
                      action="/api/file/upload"
                      :show-file-list="false"
                      :on-success="handleLicenseSuccess"
                  >
                    <img
                        v-if="ruleForm.license"
                        :src="ruleForm.license"
                        class="avatar"
                        style="height: 100px"
                        alt=""
                    />
                    <el-icon v-else class="avatar-uploader-icon">
                      <Plus/>
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="店铺照片" prop="photos">
                  <el-image
                      v-for="(url, idx) in ruleForm.photos"
                      :key="idx"
                      :src="url"
                      class="store-photos"
                      style="margin-right: 10px; height: 100px"
                      fit="cover"
                  />
                  <el-upload
                      class="store-photos-uploader"
                      action="/api/file/upload"
                      :show-file-list="false"
                      :on-success="(res, file) => handlePhotoSuccess(res, file)"
                  >
                    <el-icon class="avatar-uploader-icon">
                      <Plus/>
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="最低价" prop="priceMin">
                  <el-input
                      type="number"
                      v-model.number="ruleForm.priceMin"
                      placeholder="最低价"
                      class="filter-input"
                  />
                </el-form-item>
                <el-form-item label="最高价" prop="priceMax">
                  <el-input
                      type="number"
                      v-model.number="ruleForm.priceMax"
                      placeholder="最高价"
                      class="filter-input"
                  />
                </el-form-item>
                <el-form-item label="店铺描述" prop="description">
                  <el-input v-model="ruleForm.description" type="textarea" :rows="5"/>
                </el-form-item>
              </el-form>
            </span>
          </template>
          <template #footer>
            <div style="flex: auto">
              <el-button @click="cancelClick">取消</el-button>
              <el-button
                  type="primary"
                  @click="submitForm(ruleFormRef)"
              >
                确定
              </el-button>
            </div>
          </template>
        </el-drawer>


        <!--  店铺的评论信息  -->
        <!--        <el-table :data="users" height="310" style="width: 100%" stripe>-->
        <!--          <el-table-column prop="id" label="ID"/>-->
        <!--          <el-table-column prop="loginName" label="用户名"/>-->
        <!--          <el-table-column prop="password" label="密码"/>-->
        <!--          <el-table-column prop="remark" label="备注"/>-->
        <!--          <el-table-column prop="avatar" label="头像">-->
        <!--            <template #default="scope">-->
        <!--              <img height="50" :src="scope.row.avatar" alt="">-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--          <el-table-column label="操作">-->
        <!--            <template #default="scope">-->
        <!--              &lt;!&ndash;      scope.row表示该行数据    &ndash;&gt;-->
        <!--              <el-button type="danger" @click="removeUser(scope.row)">删除</el-button>-->
        <!--              <el-button type="primary" @click="showEditDialog(scope.row)">编辑</el-button>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--        </el-table>-->
        <!--        <br>-->
        <!--        <el-pagination-->
        <!--            v-model:current-page="pageNo"-->
        <!--            v-model:page-size="pageSize"-->
        <!--            :page-sizes="[10, 20, 50, 100]"-->
        <!--            :background="true"-->
        <!--            layout="total, sizes, prev, pager, next, jumper"-->
        <!--            :total="total"-->
        <!--            @size-change="pageSizeChange"-->
        <!--            @current-change="pageNoChange"-->
        <!--        />-->
      </div>
    </template>
  </el-card>
</template>

<style scoped lang="scss">
.page-container {
  border-top: 0;
  border-right: 0;
  border-bottom: 0;
}

.header {
  height: 25px;
  font-size: 20px;
}

.edit-store-info-btn-div {
  text-align: center; /*让div内部文字居中*/
  margin: auto;

  .edit-store-info-btn {
    font-size: 15px;
    align-content: center;
    text-align: center;
  }

}
</style>